package com.yqzl.util;

import com.fasterxml.jackson.annotation.JsonProperty;

public class Result<T> {
  private Integer code; //
  private String msg;// cg1
  //   因为这是一个泛型类，通过泛型 ，可以指定存放的是什么数据类型
//   因为前端的axios，自带一个data，如果后端数据，还是data，就会data。data。会误导，
//   JsonProperty 注解可以转换为json时将data字段改成serverData

  @JsonProperty("serverData")
  private T data;

  public Result() {
  }

  public Result(T data) {
    this.data = data;
    this.code = 200;
    this.msg = "success";
  }

  //   泛型方法  成功并携带数据
  public static <D> Result success(D data) {
    Result<D> result = new Result<>();
    result.setData(data);
    result.setCode(200);
    result.setMsg("success");
    return result;
  }

  public static Result success() {
    Result result = new Result<>();
    result.setCode(200);
    result.setMsg("success");
    return result;
  }

  public static Result fail() {
    Result result = new Result<>();
    result.setCode(500);
    result.setMsg("fail");
    return result;
  }

  public static <D> Result fail(D data) {
    Result result = new Result<>();
    result.setCode(500);
    result.setMsg(data.toString());
    return result;
  }

  public static <D> Result fail(D data, Integer code, String msg) {
    Result result = new Result<D>();
    result.setData(data);
    result.setCode(code);
    result.setMsg(msg);
    return result;
  }

  // 要提供get方法 不然提不到数据转换为json
  public Integer getCode() {
    return code;
  }

  public void setCode(Integer code) {
    this.code = code;
  }

  public String getMsg() {
    return msg;
  }

  public Result setMsg(String msg) {
    this.msg = msg;
    return this;
  }

  public T getData() {
    return data;
  }

  public Result setData(T data) {
    this.data = data;
    return this;
  }
}
